using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGourd.Core;
using NGourd.Core.Reports;

namespace NGourd
{
    public class NUnitReporter : IReporter
    {
        private readonly IFileSystemService service;
        private readonly string outputFileName;
        private const string PREFIX = @"<?xml version=""1.0"" encoding=""utf-8"" standalone=""no""?>
<test-results name=""NGourd Feature Tests"" total=""{0}"" failures=""{1}"" not-run=""{2}"" date=""{3}"" time=""{4}"">";
        private const string SUFFIX = "</test-results>";

        public NUnitReporter(IFileSystemService service, string outputFileName)
        {
            this.service = service;
            this.outputFileName = outputFileName;
        }

        public void PrintReport(ReportNode report)
        {
            service.WriteToFile(outputFileName, BuildReport(report));
        }

        private string BuildReport(ReportNode report)
        {
            var visitor = new NUnitReportNodeVisitor();
            report.Accept(visitor);
            var flattenedCollection = report.Flatten();
            var preamble = String.Format(PREFIX,
                 flattenedCollection.Count(n => n.TargetType == ReportTarget.STEP),
                 flattenedCollection.Count(n => n.TargetType == ReportTarget.STEP && n.Status == ReportStatus.FAILED),
                 flattenedCollection.Count(n => n.TargetType == ReportTarget.STEP && n.Status == ReportStatus.SKIPPED),
                 DateTime.Now.NUnitFormatDate(),
                 DateTime.Now.NUnitFormatTime()
            ); 
            
            return preamble + visitor.Result() + SUFFIX;
        }
    }

    
}
